import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';

class IconGenerator {
  static Future<void> generateIcons() async {
    // 生成主图标
    await _generateIcon(
      'assets/icons/app_icon.png',
      (canvas, size) {
        // 绘制背景
        final paint = Paint()
          ..color = const Color(0xFF2196F3)
          ..style = PaintingStyle.fill;
        canvas.drawCircle(
          Offset(size.width / 2, size.height / 2),
          size.width / 2,
          paint,
        );

        // 绘制翻译图标
        _drawTranslateIcon(canvas, Colors.white);
      },
    );

    // 生成前景图标
    await _generateIcon(
      'assets/icons/app_icon_foreground.png',
      (canvas, size) {
        _drawTranslateIcon(canvas, Colors.white);
      },
    );
  }

  static Future<void> _generateIcon(
    String path,
    void Function(Canvas canvas, Size size) draw,
  ) async {
    final size = const Size(1024, 1024);
    final recorder = ui.PictureRecorder();
    final canvas = Canvas(recorder);

    // 执行绘制
    draw(canvas, size);

    // 保存图片
    final picture = recorder.endRecording();
    final image =
        await picture.toImage(size.width.toInt(), size.height.toInt());
    final byteData = await image.toByteData(format: ui.ImageByteFormat.png);

    if (byteData != null) {
      final directory = Directory('assets/icons');
      if (!await directory.exists()) {
        await directory.create(recursive: true);
      }
      final file = File(path);
      await file.writeAsBytes(byteData.buffer.asUint8List());
    }
  }

  static void _drawTranslateIcon(Canvas canvas, Color color) {
    final paint = Paint()
      ..color = color
      ..style = PaintingStyle.fill;

    final path = Path();
    const scale = 1.0;
    const centerX = 512.0;
    const centerY = 512.0;

    // 绘制圆形
    path.addOval(
      Rect.fromCenter(
        center: const Offset(centerX, centerY),
        width: 512 * scale,
        height: 512 * scale,
      ),
    );

    // 绘制 X 形
    path.moveTo(centerX - 128 * scale, centerY - 128 * scale);
    path.lineTo(centerX + 128 * scale, centerY + 128 * scale);
    path.moveTo(centerX - 128 * scale, centerY + 128 * scale);
    path.lineTo(centerX + 128 * scale, centerY - 128 * scale);

    paint.strokeWidth = 48 * scale;
    paint.style = PaintingStyle.stroke;
    canvas.drawPath(path, paint);
  }
}
